package com.nbx.app.zeuscmdport;

import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;

/**
 * http://www.zeuscmd.com/tutorials/opengles/08-ColorAndShading.php
 * 
 */
public class Render08 extends RenderBase {
	private final static String TAG_RENDER = "Render";
	
	public Render08(Context context) {
		super(context);
	}

	private float triangle[] = {
			0.25f, 0.25f, 0.0f, 
			0.75f, 0.25f, 0.0f, 
			0.25f, 0.75f, 0.0f};

	private float colors[] = {
			1.0f, 0.0f, 0.0f, 1.0f, 
			0.0f, 1.0f, 0.0f, 1.0f, 
			0.0f, 0.0f, 1.0f, 1.0f};

	private boolean shaded = false;
		
	private FloatBuffer mTriangleBuffer;
	private FloatBuffer mColorBuffer;

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		Log.i(TAG_RENDER, "onSurfaceCreated");
		// preparation
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

		mTriangleBuffer = createFloatBuffer(triangle);
		mColorBuffer = createFloatBuffer(colors);
		
		gl.glClearColor (0.0f, 0.0f, 0.0f, 0.0f);

		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleBuffer);
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		
		gl.glShadeModel(GL10.GL_FLAT);
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		Log.i(TAG_RENDER, "onSurfaceChanged");

		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glOrthof(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f);			
	}

	public void onDrawFrame(GL10 gl) {
		Log.i(TAG_RENDER, "onDrawFrame");

		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		
		if(shaded){
			gl.glShadeModel(GL10.GL_SMOOTH);
		}else{
			gl.glShadeModel(GL10.GL_FLAT);
		}
		
		gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
	}
	
	@Override
	public boolean handleTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			shaded = !shaded;
			return true;
		}
		return false;
	}	
}